from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from cart.models import CartModel
from cart.cartser import CartSerializer
from utils.authorization import MyAuthorization
# Create your views here.
class AddCart(APIView):
    authentication_classes = [MyAuthorization, ]
    def post(self, request):
        user= request.data.get('user','')
        course= request.data.get('course','')
        if user and course:
            info = CartModel.objects.filter(user=user, course=course)
            if info:
                return Response({"massage":"课程已经存在"})
            else:
                ser = CartSerializer(data=request.data)
                if ser.is_valid():
                    ser.save()
                    return Response({"massage":"添加成功"})
                else:
                    return Response({"massage":ser.errors})
        else:
            return Response({'datial':'参数错误!'})
class CartList(APIView):
    authentication_classes = [MyAuthorization]
    def get(self,request):
        user = request.query_params.get('user')
        if user=='':
            return Response({'detial':'参数错误!'})
        cart = CartModel.objects.filter(user=user)
        ser = CartSerializer(cart,many=True)
        return Response({'massage':'success','data':ser.data})
class ChangeOne(APIView):
    authentication_classes = [MyAuthorization]
    def put(self,request):
        id = request.data.get('id','')
        if id=='':
            return Response({'detial':'参数错误!'})
        cart = CartModel.objects.filter(id=id).first()
        cart.select = not cart.select
        cart.save()
        return Response({'massage':"修改成功"})
class ChangeAll(APIView):
    authentication_classes = [MyAuthorization]
    def put(self,request):
        user = request.data.get('user','')
        select = request.data.get('select','')
        if user=='':
            return Response({'detial':'参数错误!'})
        cart = CartModel.objects.filter(user=user)
        for i in cart:
            i.select = select
            i.save()
        return Response({'massage':"修改成功"})
class DeleteCart(APIView):
    def delete(self, request):
        id = request.query_params.get('course_id','')
        print(id)
        if id=='':
            return Response({'detial':'参数错误!'})
        CartModel.objects.filter(id=id).delete()
        return Response({'massage':"删除成功"})